package cn.zyjblogs.starter.oauth.interceptor;

import cn.zyjblogs.starter.common.entity.constant.HttpHeaderConstant;
import cn.zyjblogs.starter.common.entity.context.BaseContext;
import feign.RequestInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhuyijun
 */
@Configuration
@ConditionalOnClass(RequestInterceptor.class)
public class OauthFeignInterceptorAutoConfiguration {

    @Bean
    public RequestInterceptor oauthFeignRequestInterceptor() {
        return template -> {
            String token = BaseContext.getToken();
            if (StringUtils.isNotEmpty(token)) {
                token = tokenCompletion(token);
                template.header(HttpHeaderConstant.AUTHORIZATION, token);
            }
            template.header(HttpHeaderConstant.REQUEST_FROM_FEIGN_KEY, HttpHeaderConstant.REQUEST_FROM_FEIGN_VALUE);
        };
    }

    /**
     * token信息补全,token不能为空
     *
     * @return 补全后得token
     * @author liuweicheng
     * @date 2022/03/12
     */
    private String tokenCompletion(String token) {
        String bearer = token.substring(0, HttpHeaderConstant.BEARER_TYPE.length());
        if (!HttpHeaderConstant.BEARER_TYPE.equalsIgnoreCase(bearer)) {
            token = HttpHeaderConstant.BEARER_TYPE + " " + token;
        }
        return token;
    }

}
